#coding=utf-8
#author__ = "jack"

from django.shortcuts import render

#from rest_framework.decorators import api_view
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from webuser.models import UserBase
from webuser.serializers import UserBaseSerializer
from rest_framework import generics
#from rest_framework import viewsets

# Create your views here.
#第一种方法
class UserBaseList(APIView):

    def get(self, request, format=None):
            users = UserBase.objects.all()
            serializer = UserBaseSerializer(users, many = True)
            return Response(serializer.data)

    def post(self,request, format=None):
            serializer = UserBaseSerializer(data = request.data)
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data, status = status.HTTP_201_CREATED)
            else:
                return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST)

# 通用方法
class UserBaseCreate(generics.ListCreateAPIView):
    queryset = UserBase.objects.all()
    serializer_class = UserBaseSerializer

class UserBserDetail(generics.ListCreateAPIView):
    serializer_class = UserBaseSerializer

    def get(self, request, *args, **kwargs):
        #user = UserBase.objects.get(pk = kwargs["pk"])
        user = UserBase.objects.get(pk=kwargs["pk"])    #pk只是一个Model实例的属性，如果您希望通用访问(可能是自定义的)主键字段用pk
        serializer = UserBaseSerializer(user)
        return Response(serializer.data,status = status.HTTP_201_CREATED)

    def post(self, request, *args, **kwargs):
        serializer = UserBaseSerializer(data = request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status = status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST)

# # 装饰器
# @api_view(['GET','POST'])
# def user_detail(request, pk):
# 	try:
# 		user = UserBase.objects.get(pk = pk)
# 	except Exception, e:
# 		return Response(status = status.HTTP_404_NOT_FOUND)

# 	if request.method == 'GET':
# 		serializer = UserBaseSerializer(user)
# 		return Response(serializer.data)

# 	if request.method == 'POST':
# 		serializer = UserBaseSerializer(data = request.data)
# 		if serializer.is_valid():
# 			serializer.save()
# 			return Response(serializer.data, status = status.HTTP_201_CREATED)
# 		else:
# 			return Response(serializer.errors, status = status.HTTP_400_BAD_REQUEST)